package cn.lixufeng.basic.interceptor;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.concurrent.TimeUnit;

@Component  //注解把这个拦截器交给容器管理
/**
 * 后端登录拦截器,第二个执行的拦截器，实现的HandleInterceptor，重写preHandle方法
 */
public class LoginInterceptor implements HandlerInterceptor {

    @Autowired
    private RedisTemplate redisTemplate;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws IOException {
        String token = request.getHeader("token");// UUID生成的全局唯一字符串token
        // 如果前端有token
        if(!StringUtils.isEmpty(token)) {
            Object loginTmp = redisTemplate.opsForValue().get(token);
            // 如果临时登录信息为空，那么重新刷新过期时间到30分钟
            if(loginTmp != null){

                redisTemplate.opsForValue().set(token,loginTmp,30, TimeUnit.MINUTES);

                //@TODO 权限校验，以后再做
                // 放行
                return true;
            }
        }
        // 如果前端没有传token或redis已过期
        response.setContentType("application/json;charset=UTF-8");
        response.setCharacterEncoding("UTF-8");
        PrintWriter writer = response.getWriter();
        writer.write("{\"success\":false,\"message\":\"noLogin\"}");
        writer.close();
        // 不放行
        return false;
    }
}
